package com.small.flowable.config;

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.context.annotation.Configuration;

/**
 * 获取客户端token
 *
 * @author wangguochao
 */
@Configuration
@Slf4j
public class ClientCredentials {
    private String accessToken;
    private long expiresIn;


    public ClientCredentials() {
        log.error("ClientCredentials");
//        this.intoToken();
    }

    public String getToken() {
        log.error("getToken");
        if (expiresIn >= System.currentTimeMillis() || accessToken == null) {
            this.intoToken();
        }
        return this.accessToken;
    }

    private void intoToken() {
        log.error("intoToken");
        HttpResponse<JsonNode> json = null;
        try {
            json = Unirest.post("http://192.168.31.177:9001/small-service-auth/oauth/token?grant_type=client_credentials")
                    .header("Authorization", "Basic d2ViLXBjOndlYi1wYy1zdGFydA==")
                    .asJson();
            JsonNode body = json.getBody();
            JSONObject object = body.getObject();
            log.error("object========");
            this.accessToken = object.getString("access_token");
            this.expiresIn = object.getLong("expires_in") * 1000 + System.currentTimeMillis();
        } catch (UnirestException e) {
            e.printStackTrace();
        }

    }
}
